import React,{Component} from 'react'
import $ from 'jquery'
import * as pub from '../../config/public';
import * as fetch from '../../config/fetch';
import {Spin,message} from 'antd'
import Pages from '../Pages'
import Dropzone from 'react-dropzone'
class CommodityType extends Component {
 	constructor(props) {
 		super(props)
 		this.state = {
 			categoriesList:[],
 			add:false,
 			loading:false,
			activeIndex:this.props.activeIndex,
			jumpPage:1
 		}
 	}
	componentWillReceiveProps(nextProps) {
		this.setState({
			categoriesList: []
		}, () => {
			this.setState({
				activeIndex: nextProps.activeIndex
			}, () => {
				this.show();
			})
		})
	}
	componentWillMount() {
		this.show();
	}
	show() {
		this.setState({
			categoriesList: []
		}, () => {

			let pidType = {};
			if (this.state.activeIndex === 1) {
				pidType = {
					pid: 0,
					pageno:this.state.jumpPage
				}
			} else if (this.state.activeIndex === 2) {
				pidType = {
					pid: 1,
					pageno:this.state.jumpPage
				}
			} else {
				pidType = {
					pid: 2,
					pageno:this.state.jumpPage
				}
			}
			pub.loading(this, true);
			fetch.setGoodType(pidType).then((data) => {
				if (data.result === 'RC100') {
					this.setState({
						categoriesList: data.categoriesList ? data.categoriesList : [],
						add: false,
						loading: false,
						totalPage:data.totalPage
					})
				} else {
					message.error(data.errMsg, 3);
					pub.loading(this, false);
					this.setState({
						categoriesList: []
					})
				}
				pub.loading(this, false);
			}, (res) => {
				this.setState({
					categoriesList: []
				})
				pub.loading(this, false);
				pub.reject(res);
			})

		})

	}
	save() {
		let pidType={};
	    if(this.state.activeIndex===1){
		    pidType={pid:0,
			name: this.refs.add_categories.value,}
		}else if(this.state.activeIndex===2){
			pidType={pid:1,
			name: this.refs.add_categories.value,}
		}else{
			pidType={pid:2,
			name: this.refs.add_categories.value,}
		}
		fetch.categoriesManage(pidType).then((data) => {
			if (data.result === 'RC100') {
				this.show();
			} else {
				message.error(data.errMsg, 3);
			}
		})
	}
 	change(index,item){
 		$(`#remove${index}`).prop('disabled',false);
		 $(`#edit${index}`).prop('class','icon-save');
 	}
	edit(index, item) {
        let pidType={};
       
	    if(this.state.activeIndex===1){
		    pidType={pid:0}
		}else if(this.state.activeIndex===2){
			pidType={pid:1}
		}else{
			pidType={pid:2}
		}
		if(item.code==='171207154510'){
           message.error('兑换码不可以修改！');
		   this.show();
		   $(`#edit${index}`).prop('class','icon-edit');
		}else{
			fetch.categoriesManage(Object.assign(pidType,{
				name: $(`#remove${index}`).val(),
				code: item.code,
				id: item.id,
				flag:'U'
			})).then((data) => {
				if (data.result === 'RC100') {
					$(`#edit${index}`).prop('class','icon-edit');
					this.show();
				} else {
					message.error(data.errMsg, 3);
				}
			})
		}
	}
	del(id) {
		let pidType={};
	    if(this.state.activeIndex===1){
		    pidType={pid:0}
		}else if(this.state.activeIndex===2){
			pidType={pid:1}
		}else{
			pidType={pid:2}
		}
		fetch.categoriesManage(Object.assign(pidType,{
			id: id,
			flag:'D'
		})).then((data) => {
			if (data.result === 'RC100') {
				this.show();
			} else {
				message.error(data.errMsg, 3);
			}
		})
	}
	numberInputs=(e)=>{
		let value=e.target.value;
		e.target.value=value.replace(/[@#%&{}?/><[()（）【】{}《》'“‘”’]+/g,'');
	}
	jump(page) {
		this.setState({
			jumpPage:page,
		},()=>{
			this.show();
		})
	}
 	render(){
 		return(
 			    <div className="row tab pad-t-20">
 			     <Spin spinning={this.state.loading} tip="加载列表中...">
					<ul className="good-class bg-FFFFFF box-shadow">

					    <ul id='good-list'>
					    {this.state.categoriesList.map((item,index)=>{
					    	return(
					    		<li key={index}>
					    		    <input type="text" id={`remove${index}`} defaultValue={item.name||''} disabled={true}  onKeyUp={this.numberInputs} />
					    		    <i className="icon-edit" id={`edit${index}`} onClick={(e)=>$(`#edit${index}`).attr('class')==='icon-save'?this.edit(index,item):this.change(index,item)}></i>
					    		    {/*<Popconfirm 
					    		        title={`确定要删除 <${item.name}> 吗?`} 
					    		        // title={'确定要删除吗?'}  
					    		        onConfirm={()=>this.del(item.id)} 
					    		        onCancel={()=>{}} okText="Yes" cancelText="No">
					    		        <i className="icon-remove "></i>
					    		    </Popconfirm>*/}
					    		</li>
					    		)
					    })}
					    
					    {this.state.add?<li>
					    	<input type="text" ref='add_categories' onKeyUp={this.numberInputs} />
					    	<i className="icon-save" onClick={()=>this.save()} ></i>
					        <i className="icon-remove " onClick={()=>{this.setState({add:false})}} ></i></li>:null}
					    </ul>

						<li className='acitve' onClick={()=>{this.setState({add:true})}}><i className="icon-plus-sign-alt active" ></i>新增</li>
					</ul>
					</Spin>
					<div className="line"></div>
		    	 	<Pages totalPage={this.state.totalPage} jump={this.jump.bind(this)}/>
				</div>
 			)
 	}
 } 
 var badgeList1=pub.getObject(2);
class HonorTitle extends Component {
 	constructor(args) {
 		super()
 		this.state = {
 			badgeList :[],
			add:false,
			honorId:'',
			honorName:'',
			honorNameAdd:'',
			honorBadge:'',
			honorBadgeAdd:'',
			gradeCondition:'',
			gradeConditionAdd:'',
			cover_image:{},
			cover_imageAdd:'',
			editIndex:''
 		}
 	}
	selectallHonor(){
		pub.loading(this,true);
		fetch.selectallHonor().then((data)=>{
			 if(data.result==='RC100'){
               this.setState({
			    badgeList:data.allHonor?data.allHonor:[]
			   },()=>{
				  badgeList1=this.state.badgeList;
				  badgeList1.forEach((item,index)=>{
					  item.isEdit='false';
				 })
			   })
			  this.setState({
				  badgeList:badgeList1
			  })
			}else{
				message.error(data.errMsg, 3);
			}
			pub.loading(this,false);
		}, (res) => {
			pub.loading(this,false);
			pub.reject(res);
		})
	}
	componentWillMount() {
		this.selectallHonor();
	}
	oprerationHonor(value){
		let formData = new FormData();
		if(value!=='add'){
	        formData.append('honorId',this.state.honorId);
			if(this.state.honorBadge===''){
			   formData.append('file', this.state.cover_image);
			}else{
			   formData.append('honorBadge', this.state.honorBadge);
			}
			formData.append('honorName', this.state.honorName);
			formData.append('gradeCondition', this.state.gradeCondition);
		}else{
			if(this.state.honorNameAdd===''){
               message.warning('请填写荣誉名称!');
			   return
			}else if(this.state.cover_imageAdd===''){
               message.warning('请上次荣誉图片!');
			   return
			}else if(this.state.gradeConditionAdd===''){
			   message.warning('请填写荣誉等级！')
			   return
			}
            formData.append('honorName', this.state.honorNameAdd);
			formData.append('file', this.state.cover_imageAdd);
			formData.append('gradeCondition', this.state.gradeConditionAdd);
		}
		pub.loading(this,true);
		fetch.oprerationHonor(formData).then((data)=>{
			if(data.result==='RC100'){
				if(this.state.add===true){
                    this.setState({
						add:false
					})
				}
				this.selectallHonor();
			}else{
				message.error(data.errMsg, 3);
			}
			pub.loading(this,false);
		}, (res) => {
			pub.loading(this,false);
			pub.reject(res);
		})
	}
 	honorNameChange(e){
		 this.setState({
			 honorName:e.target.value
		 })
 	}
	 inputChangeAdd(e){
        this.setState({
			honorNameAdd:e.target.value
		})
	 }
	gradeConChange(e){
         this.setState({
			 gradeCondition:e.target.value
		 })
	}
	gradeConChangeAdd(e){
          this.setState({
			  gradeConditionAdd:e.target.value
		  })
	}
 	saveOrEdit(e,item,x){
		 if(this.state.editIndex===''){
            if(item.isEdit==='false'){
             badgeList1[x].isEdit='true';
			 $(`.remove${x}`).prop('disabled',false);
 			 $(e.target).attr('class','icon-save');
			 this.setState({
				 honorId:item.honorId,
				 honorName:item.honorName,
				 honorBadge:item.honorBadge,
				 gradeCondition:item.gradeCondition,
				 editIndex:x,
			 })
		 }else{
			 this.oprerationHonor();
			 badgeList1[x].isEdit='false';
			 $(e.target).attr('class','icon-edit');
			 this.setState({
				 editIndex:''
			 })
		 }
		 this.setState({
			 badgeList:badgeList1
		 })
		 }else if(this.state.editIndex===x){
             this.oprerationHonor();
			 badgeList1[x].isEdit='false';
			 $(e.target).attr('class','icon-edit');
			 this.setState({
				 editIndex:''
			 })
		 }
 	}
	 chooseImage(accepted, rejected){
		this.setState({
			cover_image:accepted[0],
			honorBadge:""
		})
	}
	 chooseImageAdd(accepted, rejected){
		this.setState({
			cover_imageAdd:accepted[0],
		})
	}
	addNew(){
		   this.setState({
				   cover_imageAdd:'',
				   honorNameAdd:'',
				   gradeConditionAdd:'',
			       add:true,
				})
	}
 	render(){
 		return(
				<div className="row tab pad-t-20">
					<div className="honor-box bg-FFFFFF box-shadow">
						<ul className="clearFix">
						{this.state.badgeList.map((item,index)=>{
							return(
                        <li key={index}>
                           <h2>荣誉</h2>
								<div className="floatL">
									{
										item.isEdit==="true"?
										<img src={this.state.honorBadge===''?this.state.cover_image.preview:pub.getFile(this.state.honorBadge)} alt="bi"/>:
										<img src={pub.getFile(item.honorBadge)} alt="bi"/>
									}
									{
										item.isEdit==='true'?
										<Dropzone
										multiple={false}
										onDrop={this.chooseImage.bind(this)}
										className = {`choose-image`}
										accept="image/jpeg, image/png"
									>
                                       <label className="file">点击修改徽章</label>
									   </Dropzone>:null
									}
									
								</div>
								<div className="floatR edit">
									<div className="honor-name">
										<p>荣誉称号</p>
										{
											item.isEdit==='false'?
											<h3>{item.honorName}</h3>:
<label><input type="text" defaultValue={item.honorName} onChange={(e)=>this.honorNameChange(e)} className={`input remove${index}`}  value={this.state.honorName}/></label>
										}
									</div>
									<div className="level">
										<p>获取等级限制</p>
										{
											item.isEdit==='false'?
											<h3><span>{item.gradeCondition}</span>级</h3>:
<label><input type="text" defaultValue={item.gradeCondition} onChange={(e)=>this.gradeConChange(e)} className={`input-number remove${index}`} value={this.state.gradeCondition}/>级</label>
										}
									</div>
								</div>
								<i className="icon-edit" onClick={(e)=>this.saveOrEdit(e,item,index)} title="保存"></i>
							  </li>
								)
						})}
						{
                              this.state.add?
							<li>

                               <h2>荣誉</h2>
								<div className="floatL">
								<img src={this.state.cover_imageAdd.preview} alt=" "/>
								<Dropzone
								multiple={false}
								onDrop={this.chooseImageAdd.bind(this)}
								className = {`choose-image`}
								accept="image/jpeg, image/png"
							>
								<label htmlFor="file" className="file">点击修改徽章</label>
								</Dropzone>
								</div>
								<div className="floatR edit">
									<div className="honor-name">
										<p>荣誉称号</p>
										<label><input type="text" defaultValue="" onChange={(e)=>this.inputChangeAdd(e)}  value={this.state.honorNameAdd}/></label>
									</div>
									<div className="level">
										<p>获取等级限制</p>
										<label><input type="text" defaultValue="" onChange={(e)=>this.gradeConChangeAdd(e)} className="input-number" value={this.state.gradeConditionAdd}/>级</label>
									</div>
								</div>
								<i className="icon-save" onClick={()=>this.oprerationHonor('add')} title="保存"></i>   
							  </li>:null
									
						}
						     <li className="add" onClick={()=>{this.addNew()}}><i className="icon-plus-sign"></i></li>
						</ul>
						</div>
		</div>
 			)
 	}
 }
class BasisSet extends Component {
	constructor(args) {
		super()
		this.state = {
			activeIndex : 0
		}
			
	}
	render() {

		return (
			<div className="container">
			    <div className="filter clearFix">
					<ul className="filter-ul nav clearFix">
						<li className={this.state.activeIndex===0?'active':''} onClick={()=>{this.setState({activeIndex:0})}}><a>荣誉称号</a></li>
						<li className={this.state.activeIndex===1?'active':''} onClick={()=>{this.setState({activeIndex:1})}}><a>商品类型</a></li>
						<li className={this.state.activeIndex===2?'active':''} onClick={()=>{this.setState({activeIndex:2})}}><a>图书类型</a></li>
						<li className={this.state.activeIndex===3?'active':''} onClick={()=>{this.setState({activeIndex:3})}}><a>课程类型</a></li>
					</ul>
				</div>
				{
                   this.state.activeIndex===0?<HonorTitle/>:<CommodityType activeIndex={this.state.activeIndex}/>
				}

				    {/*this.state.activeIndex === 0 ?
				    	<HonorTitle />
				    	:
				    	<CommodityType />
				    */}
                        
			</div>

		)
	}

}
export default BasisSet

